package no.ntnu.item.ttm4115.termproject.socialmatchingrole_playeragent.gui;




import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.swing.AbstractAction;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.WindowConstants;

import no.ntnu.item.ttm4115.termproject.InitiateGroupChatFromGUI;
import no.ntnu.item.ttm4115.termproject.InitiateIMFromGUI;
import no.ntnu.item.ttm4115.termproject.Position;
import no.ntnu.item.ttm4115.termproject.extrasagent.Location;
import no.ntnu.item.ttm4115.termproject.extrasagent.Player;
import no.ntnu.item.ttm4115.termproject.extrasagent.Preferences;
import no.ntnu.item.ttm4115.termproject.playeragent.PlayerAgentSM;
import no.ntnu.item.ttm4115.termproject.playeragent.gui.MeetingPlaceGUI;
import no.ntnu.item.ttm4115.termproject.socialmatchingrole_playeragent.SocialMatchingRole_PlayerAgentSM;
import no.tellu.common.actorframe.ActorSM;
import no.tellu.common.javaframe.ActorAddress;

import org.jdesktop.layout.GroupLayout;
import org.jdesktop.layout.LayoutStyle;

/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class SocialMatchingTab extends javax.swing.JPanel{

	{
		//Set Look & Feel
		try {
			javax.swing.UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
		} catch(Exception e) {
			e.printStackTrace();
		}
	}

	private AbstractAction abstractActionTest;
	private JPanel jPanelPreferences;
	private JLabel jLabelScore;
	private JLabel jLabelPlayingGroupsUsers;
	private JList jListMatchedUsers;
	private JTabbedPane jTabbedPaneTreasurehuntGame;
	private JLabel jLabelInterests;
	private JTextArea jTextAreaAddress;
	private JTextArea jTextAreaDob;
	private AbstractAction abstractActionUpdatePreferences;
	private JButton jButtonUpdatePreferences;
	private JTextArea jTextAreaInterests;
	private JComboBox jComboBoxGender;
	private JTextArea jTextAreaUserName;
	private JLabel jLabelDob;

	private String userAddress = "Surya";
	private JList jListEmergingGroups;
	private JLabel jLabelAddress;
	private JLabel jLabelGender;
	private JLabel jLabelUserName;

	private DefaultListModel jListMatchedUsersModel= new  DefaultListModel();
	private DefaultListModel jListEmergingGroupsModel= new  DefaultListModel();
	
    private ActorSM asm;
    public ActorSM getAsm() {
		return asm;
	}

    
    private MeetingPlaceGUI meetingPlace;
	private Player player;
    private Preferences preferences;
	private Location locations;
    
	private JFrame mainFrame;

	/**
	* Auto-generated main method to display this 
	* JPanel inside a new JFrame.
	*/
	public static void main(String[] args) {

    	JFrame frame = new JFrame();
		frame.getContentPane().add(new SocialMatchingTab());
		frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
		frame.pack();
		frame.setVisible(true);
		frame.setLocationRelativeTo(null);
	}
	
	public SocialMatchingTab() {
		super();
		initGUI();
		ClueTab clueTab = new ClueTab();
		clueTab.setRootPanel(this);
		getJTabbedPaneTreasurehuntGame().addTab("Location Update", clueTab);
		jTabbedPaneTreasurehuntGame.addTab("Specify Preferences", getJPanelPreferences());
	}
	
	public SocialMatchingTab(MeetingPlaceGUI meetingPlace, Player player, ActorSM asm){
		super();
		this.meetingPlace = meetingPlace;
		this.player = player;
		this.asm = asm;
		initGUI();
		ClueTab clueTab = new ClueTab();
		clueTab.setRootPanel(this);
		getJTabbedPaneTreasurehuntGame().addTab("Location Update", clueTab);
		jTabbedPaneTreasurehuntGame.addTab("Specify Preferences", getJPanelPreferences());
	}
	
	private void initGUI() {
		try {
			GroupLayout thisLayout = new GroupLayout((JComponent)this);
			this.setLayout(thisLayout);
			thisLayout.setVerticalGroup(thisLayout.createSequentialGroup()
				.addContainerGap(16, 16)
				.add(thisLayout.createParallelGroup()
				    .add(GroupLayout.LEADING, thisLayout.createSequentialGroup()
				        .add(getJLabelPlayingGroupsUsers(), GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE)
				        .addPreferredGap(LayoutStyle.RELATED)
				        .add(getJListMatchedUsers(), 0, 89, Short.MAX_VALUE)
				        .add(16)
				        .add(getJLabelScore(), GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE)
				        .addPreferredGap(LayoutStyle.RELATED)
				        .add(getJListEmergingGroups(), 0, 101, Short.MAX_VALUE)
				        .add(79))
				    .add(GroupLayout.LEADING, getJTabbedPaneTreasurehuntGame(), 0, 325, Short.MAX_VALUE))
				.addContainerGap());
			thisLayout.setHorizontalGroup(thisLayout.createSequentialGroup()
				.addContainerGap()
				.add(thisLayout.createParallelGroup()
				    .add(GroupLayout.LEADING, getJLabelPlayingGroupsUsers(), GroupLayout.PREFERRED_SIZE, 106, GroupLayout.PREFERRED_SIZE)
				    .add(GroupLayout.LEADING, getJListMatchedUsers(), 0, 108, Short.MAX_VALUE)
				    .add(GroupLayout.LEADING, thisLayout.createSequentialGroup()
				        .add(getJLabelScore(), GroupLayout.PREFERRED_SIZE, 102, GroupLayout.PREFERRED_SIZE)
				        .add(6))
				    .add(GroupLayout.LEADING, getJListEmergingGroups(), 0, 108, Short.MAX_VALUE))
				.addPreferredGap(LayoutStyle.RELATED)
				.add(getJTabbedPaneTreasurehuntGame(), 0, 735, Short.MAX_VALUE));
			this.setPreferredSize(new java.awt.Dimension(859, 382));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public JTabbedPane getJTabbedPaneTreasurehuntGame() {
		if(jTabbedPaneTreasurehuntGame == null) {
			jTabbedPaneTreasurehuntGame = new JTabbedPane();
		}
		return jTabbedPaneTreasurehuntGame;
	}

	public JList getJListMatchedUsers() {
		if(jListMatchedUsers == null) {	
			jListMatchedUsers = new JList();
			jListMatchedUsers.setModel(getJListMatchedUsersModel());
			// test user
			//dummyUsersList();
			jListMatchedUsers.addMouseListener(
					new MouseAdapter() {
						public void mouseReleased( MouseEvent e ) {
							if (e.isPopupTrigger()) {
								popupToUserList().show( (JComponent)e.getSource(), e.getX(), e.getY() );
							}
						}
					}
			);
		}
		return jListMatchedUsers;
	}

	public JLabel getJLabelPlayingGroupsUsers() {
		if(jLabelPlayingGroupsUsers == null) {
			jLabelPlayingGroupsUsers = new JLabel();
			jLabelPlayingGroupsUsers.setText("Matched Users");
		}
		return jLabelPlayingGroupsUsers;
	}
	
	public JLabel getJLabelScore() {
		if(jLabelScore == null) {
			jLabelScore = new JLabel();
			jLabelScore.setText("Social Groups");
		}
		return jLabelScore;
	}
	
    public DefaultListModel getJListMatchedUsersModel(){ 	
    	return jListMatchedUsersModel;
    }
    
    public void drawUserList(Player p){
    	
    	//update online player map
    	((PlayerAgentSM)((SocialMatchingRole_PlayerAgentSM)asm).mainFrame.getAsm()).onlinePlayersMap.put(p.getUserName(),p);
    	
    	//redraw matched user 
    	getJListMatchedUsersModel().clear();
    	ArrayList<Integer> index = new ArrayList<Integer>();
    	for(int i=0; i< p.getMatchList().size(); i++) getJListMatchedUsersModel().addElement(p.getMatchList().get(i).getUserName()+"("+p.getMatchList().get(i).getLocation()+") "+p.getMatchList().get(i).getStatus());			 	
    
    }
    
   /* private void dummyUsersList(){
    	
    	getJListMatchedUsersModel().addElement("Test User1");
    	getJListMatchedUsersModel().addElement("Test User2");
    	getJListMatchedUsersModel().addElement("Test User3");
    	   	
   		Iterator<Map.Entry> playerit = ((PlayerAgentSM)((SocialMatchingRole_PlayerAgentSM)asm).mainFrame.getAsm()).onlinePlayersMap.entrySet().iterator();
    		while(playerit.hasNext()){
    			Map.Entry me = (Map.Entry)playerit.next();
    			Player player = (Player)me.getValue();
    			if (!this.player.getUserName().equals(player.getUserName())){
    				getJListMatchedUsersModel().addElement(player.getUserName()+"("+player.getLocation()+") "+player.getStatus());			
    			}
    		}
        	
    }*/
    
    private JPopupMenu popupToUserList(){

		JPopupMenu popup;
		JMenuItem mi;
		
		popup = new JPopupMenu();	
		
		mi = new JMenuItem("Start Chat");
		mi.addActionListener(new PopupListener());
		mi.setActionCommand("startchat");
		popup.add(mi);
			
		popup.setOpaque(true);
		popup.setLightWeightPopupEnabled(true);
		return popup;   	
	}
    
    public JPanel getJPanelPreferences() {
    	if(jPanelPreferences == null) {
    		jPanelPreferences = new JPanel();
    		GroupLayout jPanelPreferencesLayout = new GroupLayout((JComponent)jPanelPreferences);
    		jPanelPreferences.setLayout(jPanelPreferencesLayout);
    		jPanelPreferencesLayout.setHorizontalGroup(jPanelPreferencesLayout.createSequentialGroup()
    			.addContainerGap(15, 15)
    			.add(jPanelPreferencesLayout.createParallelGroup()
    			    .add(GroupLayout.LEADING, getJLabelUserName(), GroupLayout.PREFERRED_SIZE, 96, GroupLayout.PREFERRED_SIZE)
    			    .add(GroupLayout.LEADING, getJLabelGender(), GroupLayout.PREFERRED_SIZE, 96, GroupLayout.PREFERRED_SIZE)
    			    .add(GroupLayout.LEADING, getJLabelAddress(), GroupLayout.PREFERRED_SIZE, 96, GroupLayout.PREFERRED_SIZE)
    			    .add(GroupLayout.LEADING, getJLabelDob(), GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE)
    			    .add(GroupLayout.LEADING, getJLabelInterests(), GroupLayout.PREFERRED_SIZE, 96, GroupLayout.PREFERRED_SIZE))
    			.add(35)
    			.add(jPanelPreferencesLayout.createParallelGroup()
    			    .add(GroupLayout.LEADING, jPanelPreferencesLayout.createSequentialGroup()
    			        .add(getJTextAreaUserName(), GroupLayout.PREFERRED_SIZE, 388, GroupLayout.PREFERRED_SIZE)
    			        .add(6))
    			    .add(GroupLayout.LEADING, jPanelPreferencesLayout.createSequentialGroup()
    			        .add(getJComboBoxGender(), GroupLayout.PREFERRED_SIZE, 84, GroupLayout.PREFERRED_SIZE)
    			        .add(196)
    			        .add(getJButtonUpdatePreferences(), GroupLayout.PREFERRED_SIZE, 114, GroupLayout.PREFERRED_SIZE))
    			    .add(GroupLayout.LEADING, jPanelPreferencesLayout.createSequentialGroup()
    			        .add(getJTextAreaAddress(), GroupLayout.PREFERRED_SIZE, 388, GroupLayout.PREFERRED_SIZE)
    			        .add(6))
    			    .add(GroupLayout.LEADING, jPanelPreferencesLayout.createSequentialGroup()
    			        .add(getJTextAreaDob(), GroupLayout.PREFERRED_SIZE, 388, GroupLayout.PREFERRED_SIZE)
    			        .add(6))
    			    .add(GroupLayout.LEADING, jPanelPreferencesLayout.createSequentialGroup()
    			        .add(getJTextAreaInterests(), GroupLayout.PREFERRED_SIZE, 388, GroupLayout.PREFERRED_SIZE)
    			        .add(6)))
    			.addContainerGap(190, 190));
    		jPanelPreferencesLayout.setVerticalGroup(jPanelPreferencesLayout.createSequentialGroup()
    			.addContainerGap()
    			.add(jPanelPreferencesLayout.createParallelGroup()
    			    .add(GroupLayout.LEADING, jPanelPreferencesLayout.createSequentialGroup()
    			        .add(getJLabelUserName(), GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE)
    			        .add(8))
    			    .add(GroupLayout.LEADING, getJTextAreaUserName(), GroupLayout.PREFERRED_SIZE, 22, GroupLayout.PREFERRED_SIZE))
    			.addPreferredGap(LayoutStyle.RELATED)
    			.add(jPanelPreferencesLayout.createParallelGroup(GroupLayout.BASELINE)
    			    .add(GroupLayout.BASELINE, getJComboBoxGender(), GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE)
    			    .add(GroupLayout.BASELINE, getJLabelGender(), GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE))
    			.addPreferredGap(LayoutStyle.RELATED)
    			.add(jPanelPreferencesLayout.createParallelGroup()
    			    .add(GroupLayout.LEADING, getJTextAreaAddress(), GroupLayout.PREFERRED_SIZE, 22, GroupLayout.PREFERRED_SIZE)
    			    .add(GroupLayout.LEADING, jPanelPreferencesLayout.createSequentialGroup()
    			        .add(10)
    			        .add(getJLabelAddress(), GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE)))
    			.addPreferredGap(LayoutStyle.RELATED)
    			.add(jPanelPreferencesLayout.createParallelGroup()
    			    .add(GroupLayout.LEADING, getJTextAreaDob(), GroupLayout.PREFERRED_SIZE, 22, GroupLayout.PREFERRED_SIZE)
    			    .add(GroupLayout.LEADING, jPanelPreferencesLayout.createSequentialGroup()
    			        .add(7)
    			        .add(getJLabelDob(), GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE)))
    			.add(15)
    			.add(jPanelPreferencesLayout.createParallelGroup()
    			    .add(GroupLayout.LEADING, jPanelPreferencesLayout.createSequentialGroup()
    			        .add(getJLabelInterests(), GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE)
    			        .add(93))
    			    .add(GroupLayout.LEADING, getJTextAreaInterests(), GroupLayout.PREFERRED_SIZE, 107, GroupLayout.PREFERRED_SIZE))
    			.add(19)
    			.add(getJButtonUpdatePreferences(), GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE)
    			.addContainerGap(18, 18));
    	}
    	return jPanelPreferences;
    }
    
    public JList getJListEmergingGroups() {
    	if(jListEmergingGroups == null) {
    		jListEmergingGroups = new JList();
    		jListEmergingGroups.setModel(getJListEmergingGroupsModel());
    		dummyGroupsList();
    		
    		jListEmergingGroups.addMouseListener(
					new MouseAdapter() {
						public void mouseReleased( MouseEvent e ) {
							if (e.isPopupTrigger()) {
								popupToGroupsList().show( (JComponent)e.getSource(), e.getX(), e.getY() );
							}
						}
					}
			);
    	}
    	return jListEmergingGroups;
    }
    
    private JPopupMenu popupToGroupsList(){

		JPopupMenu popup;
		JMenuItem mi;
		
		popup = new JPopupMenu();	
		
		mi = new JMenuItem("Start Group Chat");
		mi.addActionListener(new PopupListener());
		mi.setActionCommand("startgroupchat");
		popup.add(mi);
			
		popup.setOpaque(true);
		popup.setLightWeightPopupEnabled(true);
		return popup;   	
	}
    
    public DefaultListModel getJListEmergingGroupsModel(){ 	
    	return jListEmergingGroupsModel;
    }
    
    private void dummyGroupsList(){
    	
    	getJListEmergingGroupsModel().addElement("Test Group1");
    	getJListEmergingGroupsModel().addElement("Test Group2");
    	getJListEmergingGroupsModel().addElement("Test Group3");
    
    
    }
    
    public void setGroupList(String group){
    	
    	getJListEmergingGroupsModel().clear();
    	getJListEmergingGroupsModel().addElement(group);
    }
    
    
    public JLabel getJLabelUserName() {
    	if(jLabelUserName == null) {
    		jLabelUserName = new JLabel();
    		jLabelUserName.setText("Name");
    	}
    	return jLabelUserName;
    }
    
    public JLabel getJLabelGender() {
    	if(jLabelGender == null) {
    		jLabelGender = new JLabel();
    		jLabelGender.setText("Gender");
    	}
    	return jLabelGender;
    }
    
    public JLabel getJLabelAddress() {
    	if(jLabelAddress == null) {
    		jLabelAddress = new JLabel();
    		jLabelAddress.setText("Address");
    	}
    	return jLabelAddress;
    }
    
    public JLabel getJLabelDob() {
    	if(jLabelDob == null) {
    		jLabelDob = new JLabel();
    		jLabelDob.setText("Date of Birth (yyyy)");
    	}
    	return jLabelDob;
    }
    
    public JLabel getJLabelInterests() {
    	if(jLabelInterests == null) {
    		jLabelInterests = new JLabel();
    		jLabelInterests.setText("Interested");
    	}
    	return jLabelInterests;
    }
    
    public JTextArea getJTextAreaUserName() {
    	if(jTextAreaUserName == null) {
    		jTextAreaUserName = new JTextArea();
    	}
    	return jTextAreaUserName;
    }
    
    public JComboBox getJComboBoxGender() {
    	if(jComboBoxGender == null) {
    		ComboBoxModel jComboBoxGenderModel = 
    			new DefaultComboBoxModel(
    					new String[] { "Male", "Female", "Other" });
    		jComboBoxGender = new JComboBox();
    		jComboBoxGender.setModel(jComboBoxGenderModel);
    	}
    	return jComboBoxGender;
    }
    
    public JTextArea getJTextAreaAddress() {
    	if(jTextAreaAddress == null) {
    		jTextAreaAddress = new JTextArea();
    	}
    	return jTextAreaAddress;
    }
    
    public JTextArea getJTextAreaDob() {
    	if(jTextAreaDob == null) {
    		jTextAreaDob = new JTextArea();
    	}
    	return jTextAreaDob;
    }
    
    public JTextArea getJTextAreaInterests() {
    	if(jTextAreaInterests == null) {
    		jTextAreaInterests = new JTextArea();
    		jTextAreaInterests.setText("Specify intererts seperated by commas");
    	}
    	return jTextAreaInterests;
    }
    
    public JButton getJButtonUpdatePreferences() {
    	if(jButtonUpdatePreferences == null) {
    		jButtonUpdatePreferences = new JButton();
    		jButtonUpdatePreferences.setText("Update");
    		jButtonUpdatePreferences.setAction(getAbstractActionUpdatePreferences());
    	}
    	return jButtonUpdatePreferences;
    }
    
    private AbstractAction getAbstractActionUpdatePreferences() {
    	if(abstractActionUpdatePreferences == null) {
    		abstractActionUpdatePreferences = new AbstractAction("Update", null) {
    			public void actionPerformed(ActionEvent evt) {
    				
    				Preferences pref = new Preferences();
    				pref.setAddress(getJTextAreaAddress().getText());
    				pref.setDob(getJTextAreaDob().getText());
    				pref.setGender(getJComboBoxGender().getSelectedItem().toString());
    				pref.setInterests(getJTextAreaInterests().getText());
    				pref.setName(getJTextAreaUserName().getText());
    				pref.setPlayer(getPlayer());
    				
    				setPreferences(pref);				
    				preferencesUpdated(pref);
    			}
    		};
    	}
    	return abstractActionUpdatePreferences;
    }
    
    
    public void updateEmergingGroups(){
    	
    }
    
    public void updateMatchedusers(Player p){
    	
    	//update online player map
    	((PlayerAgentSM)((SocialMatchingRole_PlayerAgentSM)asm).mainFrame.getAsm()).onlinePlayersMap.put(p.getUserName(),p);
    	
    	//redraw matched user 
    	getJListMatchedUsersModel().clear();
    	for(int i=0; i< p.getMatchList().size(); i++) getJListMatchedUsersModel().addElement(p.getMatchList().get(i).getUserName()+"("+p.getMatchList().get(i).getLocation()+") "+p.getMatchList().get(i).getStatus());			
    
    	
    }
    
    class PopupListener implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			if(e.getActionCommand().endsWith("startchat")){
				// write event handlers code
							
				String temp = jListMatchedUsers.getSelectedValue().toString(); 			
				meetingPlace.showIMWindow(temp);
				
			}
			if(e.getActionCommand().endsWith("startgroupchat")){
				// write event handlers code
				System.out.println("start group chat here...");
				//String temp = jListEmergingGroups.getSelectedValue().toString();
				meetingPlace.showGrChtWindow();
				
			}
		}
	}

	public String getUserAddress() {
		return userAddress;
	}

	public void setUserAddress(String userAddress) {
		this.userAddress = userAddress;
	}

	public Player getPlayer() {
		return player;
	}

	public void setPlayer(Player player) {
		this.player = player;
	}

	public Preferences getPreferences() {
		return preferences;
	}

	public void setPreferences(Preferences preferences) {
		this.preferences = preferences;
	}

	public Location getLocations() {
		return locations;
	}

	public void setLocations(Location locations) {
		this.locations = locations;
	}
	
	// Location Update Event received
	public void locationUpdated(Location locations){
		System.out.println("location updated..:"+locations);
		asm.sendMessage(new no.ntnu.item.ttm4115.termproject.Location(locations.getX(),locations.getY()),asm.getMyActorAddress());
	}

	public void preferencesUpdated(Preferences pref){
		System.out.println("preferences updated..:"+preferences);		
		asm.sendMessage(new no.ntnu.item.ttm4115.termproject.Preferences(pref.getName(),pref.getGender(), pref.getAddress(), pref.getDob(), pref.getInterests()), asm.getMyActorAddress());
	}
		
}
